package com.parkwalk.xxx.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author borball.zh@gmail.com
 * @date 2012-5-5
 * 
 */
public abstract class PropertiesLoader {

	private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);

	private Properties properties;

	protected PropertiesLoader(String... resourcesPaths) {
		properties = loadProperties(resourcesPaths);
	}

	public Properties getProperties() {
		return properties;
	}

	public String getProperty(String key) {
		String result = System.getProperty(key);
		if (result != null) {
			return result;
		}
		return properties.getProperty(key);
	}

	public String getProperty(String key, String defaultValue) {
		String result = getProperty(key);
		if (result != null) {
			return result;
		} else {
			return defaultValue;
		}
	}

	public Integer getInteger(String key) {
		return Integer.valueOf(getProperty(key));
	}

	public Integer getInteger(String key, Integer defaultValue) {
		return Integer.valueOf(getProperty(key, String.valueOf(defaultValue)));
	}

	public Boolean getBoolean(String key) {
		return Boolean.valueOf(getProperty(key));
	}

	public Boolean getBoolean(String key, boolean defaultValue) {
		return Boolean.valueOf(getProperty(key, String.valueOf(defaultValue)));
	}

	private Properties loadProperties(String... resourcesPaths) {
		Properties props = new Properties();

		for (String location : resourcesPaths) {

			logger.debug("Loading properties file from:" + location);

			InputStream is = null;
			try {
				is = PropertiesLoader.class.getClassLoader().getResourceAsStream(location);
				if (is != null)
					props.load(is);
			} catch (IOException ex) {
				logger.error("Could not load properties from path:" + location + ", " + ex.getMessage());
			} finally {
				try {
					if (is != null)
						is.close();
				} catch (IOException e) {
					logger.error("Could not close properties from path:" + location + ", " + e.getMessage());
				}
			}
		}
		return props;
	}
}